package com.fjzzct.report.utils;

import com.fjzzct.report.domain.ExcelFormat;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * Created by cwb on 2015/8/22.
 */

public class ExcelHelper {

    public static void BuildExcelByHtml(ExcelFormat data,boolean HasHeader, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setCharacterEncoding("UTF-8");
        String filename = "test.xls";
        response.setHeader("Content-Disposition", "attachment;filename=" + encodeFilename(filename, request));

        response.setContentType("application/vnd.ms-excel");

        StringBuilder sb = new StringBuilder("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=utf-8\"/>");
        sb.append("<table border=1>");
        if(data.getHeader().size()>0){
            sb.append("<thead><tr>");
            for (String header : data.getHeader()) {
                sb.append("<th>"+header+"</th>");
            }
            sb.append("</tr></thead>");
        }
        if(data.getContent().size()>0){
            sb.append("<tbody>");
            for (List<Object> objects : (List<List<Object>>)data.getContent()) {
                sb.append("<tr>");
                for (Object object : objects) {
                    String rowspan="";
                    String colspan="";
/*                    if(object.getColspan()!=0)
                    {
                        colspan="colspan='"+object.getColspan().toString()+"'";
                    }
                    if(object.getRowspan()!=0){
                        rowspan="rowspan='"+object.getRowspan().toString()+"'";
                    }*/
                    sb.append("<td>"+object+"</td>");
                }
                sb.append("</tr>");
            }

            sb.append("</tbody>");
        }
        sb.append("</table>");

        response.getWriter().write(sb.toString());
        response.getWriter().flush();
    }


/*        protected void buildExcelDocument(Map<String, Object> obj,
                                      HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        HSSFSheet sheet = workbook.createSheet("list");
        sheet.setDefaultColumnWidth((short) 12);
        HSSFCell cell = getCell(sheet, 0, 0);
        setText(cell, "Spring Excel test");
        HSSFCellStyle dateStyle = workbook.createCellStyle();
        //dateStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("mm/dd/yyyy"));
        cell = getCell(sheet, 1, 0);
        cell.setCellValue("日期：2008-10-23");
        //cell.setCellStyle(dateStyle);
        getCell(sheet, 2, 0).setCellValue("测试1");
        getCell(sheet, 2, 1).setCellValue("测试2");
        HSSFRow sheetRow = sheet.createRow(3);
        for (short i = 0; i < 10; i++) {
            sheetRow.createCell(i).setCellValue(i * 10);
        }
        String filename = "test.xls";//设置下载时客户端Excel的名称
        filename = encodeFilename(filename, request);//处理中文文件名
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + filename);
        OutputStream ouputStream = response.getOutputStream();
        workbook.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }*/

    /**
     * 设置下载文件中文件的名称
     *
     * @param filename
     * @param request
     * @return
     */
    public static String encodeFilename(String filename, HttpServletRequest request) {
        /**
         * 获取客户端浏览器和操作系统信息
         * 在IE浏览器中得到的是：User-Agent=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; Alexa Toolbar)
         * 在Firefox中得到的是：User-Agent=Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.7.10) Gecko/20050717 Firefox/1.0.6
         */
        String agent = request.getHeader("USER-AGENT");
        try {
            if ((agent != null) && (-1 != agent.indexOf("MSIE"))) {
                String newFileName = URLEncoder.encode(filename, "UTF-8");
                newFileName = StringUtils.replace(newFileName, "+", "%20");
                if (newFileName.length() > 150) {
                    newFileName = new String(filename.getBytes("GB2312"), "ISO8859-1");
                    newFileName = StringUtils.replace(newFileName, " ", "%20");
                }
                return newFileName;
            }
            else
            {
                String newFileName = URLEncoder.encode(filename, "UTF-8");
                newFileName = StringUtils.replace(newFileName, "+", "%20");
                if (newFileName.length() > 150) {
                    newFileName = new String(filename.getBytes("GB2312"), "ISO8859-1");
                    newFileName = StringUtils.replace(newFileName, " ", "%20");
                }
                return newFileName;
            }
/*            if ((agent != null) && (-1 != agent.indexOf("Mozilla")))
                return MimeUtility.encodeText(filename, "UTF-8", "B");*/

            //return filename;
        } catch (Exception ex) {
            return filename;
        }
    }
}